﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.ArrivalCheck;
using B.S.DataBase.MyProject.Domain.Sales;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.CheckCommand;
using Yitter.IdGenerator;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.CheckCommandHandler
{
    public class AddArrivalCheckCommandHandler : IRequestHandler<AddArrivalCheckCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<ArrivalCheck> arrivalCheckBiz;
        private readonly IBaseRepository<OrderMaterials> materialsBiz;

        public AddArrivalCheckCommandHandler(IMapper mapper, IBaseRepository<ArrivalCheck> arrivalCheckBiz, IBaseRepository<OrderMaterials> materialsBiz)
        {
            this.mapper = mapper;
            this.arrivalCheckBiz = arrivalCheckBiz;
            this.materialsBiz = materialsBiz;
        }

        public Task<APIResult<object>> Handle(AddArrivalCheckCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var materialsList = materialsBiz.Quary(x => x.MaterialsClass == 2).Result;
            var arrivalCheck = mapper.Map<ArrivalCheck>(request);
            arrivalCheck.Id = YitIdHelper.NextId();
            arrivalCheck.MaterialsName = string.Join('/', materialsList.Where(x => x.SaleCode == arrivalCheck.SourceId).Select(x => x.MaterialsName).ToList());
            int res = arrivalCheckBiz.Add(arrivalCheck).Result;
            if(res > 0)
            {
                result.data = arrivalCheck;
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
            }
            else
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }
            return Task.FromResult(result); 
           
        }
    }
}
